﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using IF.Utils;
using System.IO;
using Newtonsoft.Json.Linq;

namespace IFStudio
{
    public partial class AddressJiaoyan : Form
    {
        public AddressJiaoyan()
        {
            InitializeComponent();
        }

        //路径
        private string path;
        public string GetOrderPushDataParam_List(List<DataRow> para_Info, BackgroundWorker param_bgw_Process)
        {
            DataRow dtro = para_Info[0];
            Dictionary<string, object> dicReq = new Dictionary<string, object>();
            if (string.IsNullOrEmpty(dtro["平台订单编号"].ToString()))
            {
                return "";
            }
            string orderNumber = dtro["平台订单编号"].ToString().Trim() + "-1545";
            dicReq.Add("tid", orderNumber);//平台订单编号
            /**
             * 订单状态: 
             * 10未确认(等待付款的订单,cod订单不需要等付款，直接进行待发货)  
             * 20待尾款(部分付款的订单,要等尾款付完再发货) 
             * 30已付款待发货 
             * 40部分发货(拆分发货才会出现) 
             * 50已发货(平台上订单状态已经发货) 
             * 60已签收 
             * 70已完成 
             * 80已退款(付过款后来全部退款了) 
             * 90已关闭(未付款直接取消的订单)
             */
            dicReq.Add("trade_status", "30");//30已付款待发货
            dicReq.Add("pay_status", "2");//付款状态:0未付款1部分付款2已付款
            dicReq.Add("delivery_term", 4);//发货条件:1款到发货 2货到付款(包含部分货到付款)4、挂账
            dicReq.Add("trade_time", string.Format("{0:G}", DateTime.Now));//推送时间
            dicReq.Add("pay_time", string.Format("{0:G}", DateTime.Now));//支付时间
            dicReq.Add("buyer_nick", "优酷万万没想到众筹");//网名
            dicReq.Add("buyer_email", dtro["邮编地址"].ToString().Trim());//..
            dicReq.Add("pay_id", string.Empty);
            dicReq.Add("pay_account", "");//省份	城市	区
            dicReq.Add("receiver_name", dtro["收货人姓名"].ToString().Trim());
            dicReq.Add("receiver_province", "无");
            dicReq.Add("receiver_city", "无");
            dicReq.Add("receiver_district", "无");
            //dicReq.Add("receiver_address", dtro["收货地址"].ToString().Trim().Replace(dtro["收货人省份"].ToString().Trim() + dtro["收货人城市"].ToString().Trim() + dtro["收货人地区"].ToString().Trim(), string.Empty));
            dicReq.Add("receiver_address", dtro["收货地址"].ToString().Trim());
            dicReq.Add("receiver_mobile", dtro["联系手机"].ToString().Trim());
            dicReq.Add("receiver_telno", "");
            dicReq.Add("receiver_zip", string.Empty);
            dicReq.Add("logistics_type", "ZTO");
            dicReq.Add("invoice_type", 0);
            dicReq.Add("invoice_title", "");
            dicReq.Add("buyer_message", dtro["回报项"].ToString().Trim());
            dicReq.Add("seller_memo", "");
            dicReq.Add("seller_flag", "0");
            dicReq.Add("post_amount", 0);
            dicReq.Add("cod_amount", "0");
            dicReq.Add("ext_cod_fee", "0");
            dicReq.Add("paid", 0);

            List<object> detailList = new List<object>();

            foreach (DataRow item in para_Info)
            {
                var datail = new
                {
                    oid = DateTime.Now.ToFileTime().ToString(),
                    num = item["宝贝总数量"].ToString().Trim(),
                    price = item["商品价格"].ToString().Trim(),
                    status = 30,
                    refund_status = 0,
                    goods_id = "",
                    spec_id = "",
                    goods_no = string.Empty,// item.GoodNo,
                    spec_no = item["商家编码(商品)"].ToString().Trim(),// item.MerchantNo,//.Remove(0, item.GoodNo.Length),
                    goods_name = "",
                    spec_name = "",
                    adjust_amount = 0,
                    discount = 0,
                    share_discount = 0,
                    cid = ""

                };
                detailList.Add(datail);
            }

            dicReq.Add("order_list", detailList);

            List<object> list = new List<object>();
            list.Add(dicReq);

            //转成JSon
            string json = JsonConvert.SerializeObject(list);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("sid", WDTUtil.SID);
            dic.Add("appkey", WDTUtil.APPKEY);
            dic.Add("timestamp", WDTUtil.DateTimeToStamp(DateTime.Now).ToString());
            dic.Add("shop_no", WDTUtil.SHOPNO);
            dic.Add("trade_list", json);
            string resutl = WDTUtil.SendPost("/openapi2/trade_push.php", dic);
            //解析 json
            JObject obj_ProductJson = JObject.Parse(resutl);
            //状态成功
            int resultCode = Convert.ToInt32(obj_ProductJson["code"].ToString());
            //新增数量
            int orderCount = Convert.ToInt32(obj_ProductJson["new_count"].ToString());
            if (resultCode == 0 && orderCount > 0)
            {
                param_bgw_Process.ReportProgress(1, orderNumber + "---- 订单推送成功\r");
            }
            else
            {
                param_bgw_Process.ReportProgress(1, orderNumber + "订单推送失败\r");
            }
            param_bgw_Process.ReportProgress(1, "↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑\r");
            //return string.Format("{1}/trade_push.php?{0}", CreateParam(dic,true), TransConstConfig.ErpUrl);
            return resutl;

        }

        /// <summary>
        /// 只有一行数据
        /// </summary>
        /// <param name="?"></param>
        /// <param name="param_bgw_Process"></param>
        /// <returns></returns>
        public string GetOrderPushDataParam_DT(DataRow dtro, BackgroundWorker param_bgw_Process)
        {
            Dictionary<string, object> dicReq = new Dictionary<string, object>();
            string orderNumber = DateTime.Now.ToFileTime().ToString() + "1";
            dicReq.Add("tid", orderNumber);//平台订单编号
            /**
             * 订单状态: 
             * 10未确认(等待付款的订单,cod订单不需要等付款，直接进行待发货)  
             * 20待尾款(部分付款的订单,要等尾款付完再发货) 
             * 30已付款待发货 
             * 40部分发货(拆分发货才会出现) 
             * 50已发货(平台上订单状态已经发货) 
             * 60已签收 
             * 70已完成 
             * 80已退款(付过款后来全部退款了) 
             * 90已关闭(未付款直接取消的订单)
             */
            dicReq.Add("trade_status", "30");//30已付款待发货
            dicReq.Add("pay_status", "2");//付款状态:0未付款1部分付款2已付款
            dicReq.Add("delivery_term", 4);//发货条件:1款到发货 2货到付款(包含部分货到付款)4、挂账
            dicReq.Add("trade_time", string.Format("{0:G}", DateTime.Now));//推送时间
            dicReq.Add("pay_time", string.Format("{0:G}", DateTime.Now));//支付时间
            dicReq.Add("buyer_nick", "天津猫眼文化传媒有限公司");//网名
            dicReq.Add("buyer_email", string.Empty);//..
            dicReq.Add("pay_id", string.Empty);
            dicReq.Add("pay_account", "");//省份	城市	区
            dicReq.Add("receiver_name", dtro["BD"].ToString().Trim());
            dicReq.Add("receiver_province", "无");
            dicReq.Add("receiver_city", "无");
            dicReq.Add("receiver_district", "无");
            dicReq.Add("receiver_address", dtro["物料地址"].ToString().Trim());

            //JObject jobject = AddressClass.GetAddress(dtro["收货地址"].ToString().Trim());
            //dicReq.Add("receiver_province", jobject.GetValue("province").ToString());
            //dicReq.Add("receiver_city", jobject.GetValue("city").ToString());
            //dicReq.Add("receiver_district", jobject.GetValue("district").ToString());
            //dicReq.Add("receiver_address", jobject.GetValue("address").ToString());
            dicReq.Add("receiver_mobile", dtro["联系手机"].ToString().Trim());
            dicReq.Add("receiver_telno", "");
            dicReq.Add("receiver_zip", string.Empty);
            dicReq.Add("logistics_type", "SF");//ZTRM 中通热敏
            dicReq.Add("invoice_type", 0);
            dicReq.Add("invoice_title", "");
            dicReq.Add("buyer_message", dtro["影院名称"].ToString().Trim());
            dicReq.Add("seller_memo", "");
            dicReq.Add("seller_flag", "0");
            dicReq.Add("post_amount", 0);
            dicReq.Add("cod_amount", "0");
            dicReq.Add("ext_cod_fee", "0");
            dicReq.Add("paid", 0);

            List<object> detailList = new List<object>();

            var datail = new
            {
                oid = DateTime.Now.ToFileTime().ToString() + "3",
                num = dtro["NSPT0501"].ToString().Trim(),//《年兽大作战》泡泡贴纸
                price = "1",//售价
                status = 30,
                refund_status = 0,
                goods_id = "",
                spec_id = "",
                goods_no = string.Empty,// item.GoodNo,
                spec_no = "NSPT0501",//dtro["商家编码(商品)"].ToString().Trim(),// item.MerchantNo,//.Remove(0, item.GoodNo.Length),
                goods_name = "",
                spec_name = "",
                adjust_amount = 0,
                discount = 0,
                share_discount = 0,
                cid = ""

            };
            detailList.Add(datail);

            //var datail1 = new
            //{
            //    oid = DateTime.Now.ToFileTime().ToString() + "1",
            //    num = dtro["NSYZ0601"].ToString().Trim(),//《年兽大作战》原子印章
            //    price = "0.9",//售价
            //    status = 30,
            //    refund_status = 0,
            //    goods_id = "",
            //    spec_id = "",
            //    goods_no = string.Empty,// item.GoodNo,
            //    spec_no = "NSYZ0601",//dtro["商家编码(商品)"].ToString().Trim(),// item.MerchantNo,//.Remove(0, item.GoodNo.Length),
            //    goods_name = "",
            //    spec_name = "",
            //    adjust_amount = 0,
            //    discount = 0,
            //    share_discount = 0,
            //    cid = ""

            //};
            //detailList.Add(datail1);

            dicReq.Add("order_list", detailList);

            List<object> list = new List<object>();
            list.Add(dicReq);

            //转成JSon
            string json = JsonConvert.SerializeObject(list);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("sid", WDTUtil.SID);
            dic.Add("appkey", WDTUtil.APPKEY);
            dic.Add("timestamp", WDTUtil.DateTimeToStamp(DateTime.Now).ToString());
            dic.Add("shop_no", WDTUtil.SHOPNO);
            dic.Add("trade_list", json);
            string resutl = WDTUtil.SendPost("/openapi2/trade_push.php", dic);
            //解析 json
            JObject obj_ProductJson = JObject.Parse(resutl);
            //状态成功
            int resultCode = Convert.ToInt32(obj_ProductJson["code"].ToString());
            //新增数量
            int orderCount = Convert.ToInt32(obj_ProductJson["new_count"].ToString());
            if (resultCode == 0 && orderCount > 0)
            {
                param_bgw_Process.ReportProgress(1, orderNumber + "---- 订单推送成功\r");
            }
            else
            {
                param_bgw_Process.ReportProgress(1, orderNumber + "订单推送失败\r");
            }
            param_bgw_Process.ReportProgress(1, "↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑\r");
            //return string.Format("{1}/trade_push.php?{0}", CreateParam(dic,true), TransConstConfig.ErpUrl);
            return resutl;

        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(path) && string.IsNullOrEmpty(this.txt_Path.Text))
            {
                return;
            }
            if (string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(this.txt_Path.Text))
            {
                path = this.txt_Path.Text.Trim();
            }
            this.bgw_Process.RunWorkerAsync();
        }

        private void OrderImplrt_DragEnter(object sender, DragEventArgs e)
        {
            this.path = ((Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            this.txt_Path.Text = this.path;
            //this.txt_Info.Text = "准备！！！";
        }

        private void bgw_Process_DoWork(object sender, DoWorkEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            //加载 省市区信息
            AddressClass.LoadResource(@"E:\我的项目\IF\IFStudio\AnalysisAddress\Resource\省市区.xls", "Table1");
            DataTable DT = NOPIHelper.RenderDataTableFromExcel(path, "Sheet1", 0);
            Dictionary<string, List<DataRow>> orderinfo = new Dictionary<string, List<DataRow>>();
            //foreach (DataRow item in DT.Rows)
            //{
            //    if (orderinfo.Keys.Contains(item["平台订单编号"].ToString().Trim()))
            //    {
            //        orderinfo[item["平台订单编号"].ToString().Trim()].Add(item);
            //        continue;
            //    }
            //    orderinfo.Add(item["平台订单编号"].ToString().Trim(), new List<DataRow>() { item });
            //}
            //foreach (string item in orderinfo.Keys)
            //{
            //    sb.Append(GetOrderPushDataParam(orderinfo[item], this.bgw_Process) + "\r\n");
            //}
            foreach (DataRow item in DT.Rows)
            {
                sb.Append(GetOrderPushDataParam_DT(item, this.bgw_Process) + "\r\n");
            }

            e.Result = "----------处理完成----------\r\n";
        }

        private void bgw_Process_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.txt_ShowInfo.AppendText(e.UserState.ToString() + "\r\n");
        }

        private void bgw_Process_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.txt_ShowInfo.AppendText(e.Result.ToString());
        }

        private void btn_CancelOrder_Click(object sender, EventArgs e)
        {
            MaoyanUtil.CancelOrderPushDataParam();
        }
    }
}
